package com.my.test.jcdftemplate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang3.StringUtils;


public class CreateTemplate {
	//模板地址
	public static String TEMPLATE_PATH = System.getProperty("user.dir")+"/resources/jcdftemplate/" ;
	//src地址
	public static String SRC_PATH = "/my/work/jcdf-templage/mfa-target/" ;
	
	public static String TEMPLATE_FILE_ENCODING = "gb2312" ;

	public static String TEMPLATE_BL = "blservice/service/notice/NoticeBl.java" ;
	public static String TEMPLATE_BLM = "blservice/service/notice/NoticeBlManager.java" ;
	public static String TEMPLATE_IFSVC = "blservice/service/notice/IfNoticeSVC.java" ;
	public static String TEMPLATE_SVC = "blservice/service/notice/NoticeSVC.java" ;
	public static String TEMPLATE_MAPPERJAVA = "blservice/service/notice/NoticeMapper.java" ;
	public static String TEMPLATE_MAPPERXML = "blservice/service/notice/NoticeMapper.xml" ;

	public static String TEMPLATE_MODEL = "blservice/datamodel/notice/NoticeModel.java" ;

	public static String TEMPLATE_REQUEST = "web/notice/NoticeRequestHandler.java" ;
	public static String TEMPLATE_FLOWER = "web/notice/NoticeFlowHandler.java" ;
	
	public static String BLANK_8 = "        " ;
	public static String BLANK_5 = "     " ;
	public static String BLANK_4 = "    " ;
	public static String ENTER = "\r\n" ;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		Templage t = new Templage() ;
		/**
		t.setName("tech") ;
		t.setDesc("学习园地类") ;
		t.setEntry("TechInfo") ;
		
		t.addMethod(new TplMethod("corpListInit","企业学习园地信息列表初始化")) ;
		t.addMethod(new TplMethod("corpList","企业学习园地信息列表-ajax获取数据")) ;
		
		t.addMethod(new TplMethod("addInit","学习园地信息新增/修改初始化")) ;
		t.addMethod(new TplMethod("add","学习园地信息新增/修改")) ;

		t.addMethod(new TplMethod("delete","学习园地信息删除")) ;
		
		t.addMethod(new TplMethod("detail","学习园地信息详情")) ;
		
		t.addMethod(new TplMethod("listInit","平台方学习园地信息列表初始化")) ;
		t.addMethod(new TplMethod("list","平台方学习园地信息列表-ajax获取数据")) ;

		t.addMethod(new TplMethod("auditInit","学习园地信息审核初始化")) ;
		t.addMethod(new TplMethod("audit","学习园地信息审核")) ;

		t.addMethod(new TplMethod("publish","学习园地信息发布/撤销")) ;
		
		t.setName("common") ;
		t.setDesc("通用处理 类") ;
		t.setEntry("FileInfo") ;
		t.addMethod(new TplMethod("uploadFile","文件上传")) ;
		t.addMethod(new TplMethod("downloadFile","文件下载")) ;
		//t.addMethod(new TplMethod("showImg","通过图片流显示")) ;
		
		**/
	}
	
	public static void create(Templage t){

		//doMapper(t) ;
		doIFSVC(t) ;
		doSVC(t) ;
		doBlM(t) ;
		doBl(t) ;
		
		doModel(t) ;
		
		doRequest(t) ;
		doFlower(t) ;
		
		doRequestXml(t) ;
		doViewXml(t) ;
	}

	private static void doViewXml(Templage t){

		StringBuilder m = new StringBuilder();
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_4).append("<!-- "+t.getDesc()+"-"+tm.getDesc()+" -->") ;
			m.append(ENTER).append(BLANK_4).append("<view>") ;
			m.append(ENTER).append(BLANK_8).append("<view-name>"+t.getName()+"_"+tm.getName()+"</view-name>") ;
			m.append(ENTER).append(BLANK_8).append("<template>/WEB-INF/jsp/"+t.getName()+"/"+t.getName()+"_"+tm.getName()+".jsp</template>") ;
			m.append(ENTER).append(BLANK_4).append("</view>") ;
		}
		
		
		System.out.println(m.toString());
		
	}
	private static void doRequestXml(Templage t){

		StringBuilder m = new StringBuilder();
		m.append(ENTER).append(BLANK_4).append("<!-- "+t.getDesc()+" -->") ;
		m.append(ENTER).append(BLANK_4).append("<url-pattern url=\"/"+t.getName()+"\" usePreProcessHandler=\"true\" useRequestHandler=\"true\" useFlowHandler=\"true\">") ;
		m.append(ENTER).append(BLANK_8).append("<request-handler-class>com.mfa.web."+t.getName()+"."+t.getFirstUpperName()+"RequestHandler</request-handler-class>") ;
		m.append(ENTER).append(BLANK_8).append("<flow-handler class=\"com.mfa.web."+t.getName()+"."+t.getFirstUpperName()+"FlowHandler\">") ;
		
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_8+BLANK_4).append("<handler-result result=\""+t.getName()+"_"+tm.getName()+"\" view=\""+t.getName()+"_"+tm.getName()+"\" />") ;
		}
		
		m.append(ENTER).append(BLANK_8).append("</flow-handler>") ;
		m.append(ENTER).append(BLANK_4).append("</url-pattern>") ;
		
		System.out.println(m.toString());
		
	}
	

	private static void doFlower(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_FLOWER,t) ;
		//生成方法
		StringBuilder m = new StringBuilder();
		int i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_8).append("//"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_8).append("else if (actionType.equals(\""+getAction(t,tm)+"\")) {") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("return "+getAction(t,tm)+"();") ;
			m.append(ENTER).append(BLANK_8).append("}") ;
			i++ ;
		}
		content = content.replace("#method_flower1#", m.toString()) ;
		
		m = new StringBuilder();
		i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_4).append("/**") ;
			m.append(ENTER).append(BLANK_5).append("*"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_5).append("*/") ;
			m.append(ENTER).append(BLANK_4).append("protected String "+getAction(t,tm)+"()  throws AppFailException {") ;
			m.append(ENTER).append(BLANK_8).append("JResultModel resultModel = WebHelper.getResultModel(_req);") ;
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8).append("return null ;") ;
			m.append(ENTER).append(BLANK_4).append("}") ;
			i++ ;
		}
		content = content.replace("#method_flower2#", m.toString()) ;
		
		
		write(TEMPLATE_FLOWER,content,t);
	}
	
	private static void doRequest(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_REQUEST,t) ;
		//生成方法
		StringBuilder m = new StringBuilder();
		int i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_8).append("//"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_8).append("else if (actionType.equals(\""+getAction(t,tm)+"\")) {") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("return "+getAction(t,tm)+"();") ;
			m.append(ENTER).append(BLANK_8).append("}") ;
			i++ ;
		}
		content = content.replace("#method_request1#", m.toString()) ;
		
		m = new StringBuilder();
		i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_4).append("/**") ;
			m.append(ENTER).append(BLANK_5).append("*"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_5).append("*/") ;
			m.append(ENTER).append(BLANK_4).append("protected IfJpackageModel "+getAction(t,tm)+"()  throws AppFailException {") ;
			String entry = StringUtils.isBlank(t.getEntry())?"Test":t.getEntry();
			m.append(ENTER).append(BLANK_8).append((StringUtils.isBlank(t.getEntry())?"//":"") + entry + " " + firstLower(entry)+ " = Mapping.convertObjectFromRequest("+entry + ".class, _req) ;") ;
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8).append("//组织数据传输到svc") ;
			m.append(ENTER).append(BLANK_8).append(t.getFirstUpperName() + "Model model = new "+t.getFirstUpperName() + "Model() ;") ;
			m.append(ENTER).append(BLANK_8).append((StringUtils.isBlank(t.getEntry())?"//":"") + "model.put(\""+firstLower(entry) + "\","+firstLower(entry)+") ;") ;
			m.append(ENTER).append(BLANK_8).append("model.setActionType(\""+getAction(t,tm) + "\") ;") ;
			
			m.append(ENTER).append(BLANK_8).append("return model;") ;
			m.append(ENTER).append(BLANK_4).append("}") ;
			i++ ;
		}
		content = content.replace("#method_request2#", m.toString()) ;
		
		
		write(TEMPLATE_REQUEST,content,t);
	}
	

	private static void doModel(Templage t){
		String content = getContent(TEMPLATE_PATH + TEMPLATE_MODEL,t) ;
		write(TEMPLATE_MODEL,content,t);
	}

	private static void doMapper(Templage t){
		//java
		String content = getContent(TEMPLATE_PATH + TEMPLATE_MAPPERJAVA,t) ;
		write(TEMPLATE_MAPPERJAVA,content,t);
		//xml
		content = getContent(TEMPLATE_PATH + TEMPLATE_MAPPERXML,t) ;
		write(TEMPLATE_MAPPERXML,content,t);
	}
	private static void doIFSVC(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_IFSVC,t) ;
		//生成方法
		StringBuilder m = new StringBuilder();
		int i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_4).append("/**") ;
			m.append(ENTER).append(BLANK_5).append("*"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_5).append("*/") ;
			m.append(ENTER).append(BLANK_4).append("public JResultModel "+getAction(t,tm)+"(JpackageModel model) throws ServiceAppException;") ;
			m.append(ENTER);
			m.append(ENTER);
			i++ ;
		}
		content = content.replace("#method_ifsvc#", m.toString()) ;
		
		write(TEMPLATE_IFSVC,content,t);
	}
	
	private static void doSVC(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_SVC,t) ;
		//生成方法
		StringBuilder m = new StringBuilder();
		int i = 0 ;
		for(TplMethod tm : t.getMethodList()){

			m.append(ENTER).append(BLANK_4).append("/**") ;
			m.append(ENTER).append(BLANK_5).append("* "+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_5).append("*/") ;
			m.append(ENTER).append(BLANK_4).append("public JResultModel "+getAction(t,tm)+"(JpackageModel model) throws ServiceAppException{") ;
			//m.append(ENTER).append(BLANK_8).append("//取得条件Map") ;
			//m.append(ENTER).append(BLANK_8).append("Map pMap = (Map)model.get(\""+t.getName()+"Map\");") ;
			m.append(ENTER).append(BLANK_8).append("//取得实体类") ;
			String entry = StringUtils.isBlank(t.getEntry())?"Test":t.getEntry();
			m.append(ENTER).append(BLANK_8).append((StringUtils.isBlank(t.getEntry())?"//":"") + entry + " "+firstLower(entry)+" = ("+entry+")model.get(\""+firstLower(entry)+"\");") ;
			m.append(ENTER).append(BLANK_8).append("SqlSession sqlSession = null ;") ;
			m.append(ENTER).append(BLANK_8).append("try{") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("sqlSession = MyBatisHelper.openSession();") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append(t.getFirstUpperName()+"Mapper mapper = sqlSession.getMapper("+t.getFirstUpperName()+"Mapper.class);") ;
			m.append(ENTER).append(BLANK_8+BLANK_4);
			m.append(ENTER).append(BLANK_8+BLANK_4);
			m.append(ENTER).append(BLANK_8+BLANK_4).append("//sqlSession.commit();") ;
			m.append(ENTER).append(BLANK_8).append("}catch(Exception e){") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("e.printStackTrace();") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("//MyBatisHelper.rollback(sqlSession);") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("LogWriter.error(\"svc异常：\" ,e) ;") ;
			m.append(ENTER).append(BLANK_8).append("}finally{") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("MyBatisHelper.closeSession(sqlSession) ;") ;
			m.append(ENTER).append(BLANK_8).append("}") ;
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8).append("//创建返回结果Model") ;
			m.append(ENTER).append(BLANK_8).append("JResultModel resultModel = createResultModel();") ;
			m.append(ENTER).append(BLANK_8);
			m.append(ENTER).append(BLANK_8).append("return resultModel;") ;
			m.append(ENTER).append(BLANK_4).append("}") ;
			m.append(ENTER);
			m.append(ENTER);
			i++ ;
		}
		content = content.replace("#method_svc#", m.toString()) ;
		
		write(TEMPLATE_SVC,content,t);
	}
	private static void doBlM(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_BLM,t) ;
		
		write(TEMPLATE_BLM,content,t);
	}
	private static void doBl(Templage t){
		
		String content = getContent(TEMPLATE_PATH + TEMPLATE_BL,t) ;
		//生成方法
		StringBuilder m = new StringBuilder();
		int i = 0 ;
		for(TplMethod tm : t.getMethodList()){
			
			m.append(ENTER).append(BLANK_8).append("//"+tm.getDesc()) ;
			m.append(ENTER).append(BLANK_8).append((i==0?"if":"else if") + " (\""+getAction(t,tm)+"\".equals(actionType)) {") ;
			m.append(ENTER).append(BLANK_8+BLANK_4).append("return _svc."+getAction(t,tm)+"("+t.getName()+"Model);") ;
			m.append(ENTER).append(BLANK_8).append("}") ;
			i++ ;
		}
		content = content.replace("#method_bl#", m.toString()) ;
		write(TEMPLATE_BL,content,t);
	}

	public static String getAction(Templage t,TplMethod tm) {
		return t.getName() + "_" + tm.getName() ;
	}
	
	/**
	 * 获取文件内容
	 * @param file
	 * @return
	 */
	public static String getContent(String path,Templage t) {
		try {
//			FileReader read = new FileReader(new File(path));
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), TEMPLATE_FILE_ENCODING));
			StringBuilder content = new StringBuilder();

			while (br.ready() != false) {
				content.append(new String(br.readLine().getBytes()));
				content.append("\r\n");
			}
			br.close();
//			read.close();
			
			String c = content.toString() ;
			return c.replaceAll("#name#", t.getName())
					.replaceAll("#Name#", t.getFirstUpperName())
					.replaceAll("#desc#", t.getDesc())
					.replaceAll("#entry#", t.getEntry()) ;
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		}
		return "" ;
	}
	
	public static void write(String path,String content ,Templage t) {
		try {
			File file = new File(SRC_PATH
					+path.replace("notice", t.getName()).replace("Notice", t.getFirstUpperName())) ;
			File p = file.getParentFile() ;
			if(!p.exists()){
				p.mkdirs() ;
			}
			FileOutputStream fs = new FileOutputStream(file);
			//OutputStreamWriter osw = new OutputStreamWriter(fs, "UTF-8"); 
//			fs.write(content.getBytes("UTF-8"));
			fs.write(content.getBytes("gb2312"));
			//osw.flush();
			//osw.close();
			fs.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		}

	}
	
	public static String firstLower(String name) {
		return name.substring(0, 1).toLowerCase() + name.substring(1);
	}
	

}
